package com.crazymakercircle.dhptester.client;

import com.alibaba.fastjson.JSONObject;
import com.crazymakercircle.dhptester.benchmark.HttpBenchmark;
import com.crazymakercircle.dhptester.handler.DhpTesterHandler;
import com.crazymakercircle.handler.ExceptionHandler;
import com.crazymakercircle.util.ThreadUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpContentDecompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.util.concurrent.DefaultThreadFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

public class DhpTesterNettyClient
{
    private String host;
    private int port;
    private int client_num;
    private JSONObject jsondata;
    HttpBenchmark httpBenchmark = null;
    private Logger logger;

    public DhpTesterNettyClient(String host, int port, int client_num, JSONObject jsondata, HttpBenchmark httpBenchmark)
    {
        this.host = host;
        this.port = port;
        this.client_num = client_num;
        this.jsondata = jsondata;
        this.httpBenchmark = httpBenchmark;

        this.logger = LogManager.getLogger(DhpTesterNettyClient.class.getName());
    }

    public void start() throws Exception
    {
        EventLoopGroup group;
        group = new NioEventLoopGroup(httpBenchmark.thread_number, new DefaultThreadFactory("client", true));
        ;
//        group = new NioEventLoopGroup();

        try
        {
            Bootstrap b = new Bootstrap();
            b.group(group);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.TCP_NODELAY, true);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>()
            {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception
                {

                    ch.pipeline().addLast(new HttpClientCodec()); // http客户端编解码器
                    ch.pipeline().addLast(new HttpObjectAggregator(65536)); // http消息聚合器
                    ch.pipeline().addLast(new HttpContentDecompressor()); // 数据解压处理器

                    ch.pipeline().addLast(new DhpTesterHandler(host, port, httpBenchmark.end_time, jsondata, httpBenchmark));
                    ch.pipeline().addLast(new ExceptionHandler());
                }
            });


            httpBenchmark.start_time = System.currentTimeMillis();

            ArrayList<ChannelFuture> channelfuture_list = new ArrayList<ChannelFuture>();
            for (int i = 0; i < this.client_num; i++)
            {
                ChannelFuture f = b.connect(this.host, this.port);
                channelfuture_list.add(f);
            }


            logger.info("all client sockets init success，to:"+this.host);

//            for (int i = 0; i < channelfuture_list.size(); i++) {
//                channelfuture_list.get(i).channel().closeFuture().sync();
//            }

            while (!httpBenchmark.isOver)
            {
                ThreadUtil.sleepMilliSeconds(1000);

                checkOver();
            }
            logger.info("all client sockets shut down success");
        } finally
        {
            logger.info("group.shutdownGracefully()");
            group.shutdownGracefully();
        }
    }

    ConcurrentHashMap<Long, Boolean> flags = new ConcurrentHashMap<>();


    public void checkOver()
    {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String ct = sdf.format(date);
        //System.err.println(ct);
        long total_req_res_value = httpBenchmark.total_req_res.longValue();
        DecimalFormat df = new DecimalFormat("0.00");
//        double elapsed = (System.currentTimeMillis() - httpBenchmark.start_time) / 1000.0;
//        String qps = df.format((total_req_res_value / (elapsed)));
        if (total_req_res_value >= httpBenchmark.test_count
                || httpBenchmark.total_err.longValue() >= httpBenchmark.test_count
                || (httpBenchmark.total_err.longValue() + total_req_res_value)>httpBenchmark.test_count)
        {
            httpBenchmark.end_time = System.currentTimeMillis();
            httpBenchmark.isOver = true;
            return;
        }
        long flag = (total_req_res_value * 100 / httpBenchmark.test_count) % 10;
//        if (flag == 0 && null == flags.get(flag)) {
        flags.put(flag, true);
        long total_err_count_value = httpBenchmark.total_err.longValue();
        long total_req_count_value = httpBenchmark.total_req.longValue();
        logger.info(" == request percent = % " + (total_req_count_value * 100 / httpBenchmark.test_count));
        logger.info(" error percent = % " + (total_err_count_value * 100 / httpBenchmark.test_count));
        logger.info(" progress  = % " + (total_req_res_value * 100 / httpBenchmark.test_count));

//        }


    }

}
